package com.mdp.oauth2.server.service;

import com.mdp.oauth2.server.integration.authenticator.IntegrationAuthenticator;
import com.mdp.oauth2.server.integration.IntegrationParams;
import com.mdp.oauth2.server.integration.IntegrationParamsContext;
import com.mdp.plat.client.entity.PlatformVo;
import com.mdp.qx.DataLvl;
import com.mdp.safe.client.entity.CommonUserDetails;
import com.mdp.safe.client.entity.SafeAuthority;
import com.mdp.safe.client.entity.User;
import com.mdp.tpa.client.entity.AppShopConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * UserDetailsServiceImpl
 *
 * @author chenyc
 * @date 2021/01/11
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    Map<String,UserDetails> cache=new ConcurrentHashMap<>();

    private List<IntegrationAuthenticator> authenticators;

    @Autowired
    private PasswordEncoder passwordEncoder;

    Logger logger= LoggerFactory.getLogger(UserDetailsServiceImpl.class);


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            IntegrationParams integrationParams = IntegrationParamsContext.get();
            if(!StringUtils.hasText(integrationParams.getUserloginid())){
                integrationParams.setUserloginid(username);
            }
            try {
                String userType=integrationParams.getUserType();
                CommonUserDetails ud=null;
                IntegrationAuthenticator authenticator=this.findIntegrationAuthenticator(integrationParams);
                User user= authenticator.authenticate(integrationParams);
                if(user==null){
                    return null;
                }
                user.setUserType(userType);
                ud=CommonUserDetails.fromUser(user);
                Set<GrantedAuthority> safeAuthorities= (Set<GrantedAuthority>) authenticator.loadAuthorities(user,integrationParams);

                ud.setAuthorities(safeAuthorities);
                return ud;
            }catch (Exception e){
                logger.error("",e);
                throw e;
            }

    }



    public IntegrationAuthenticator findIntegrationAuthenticator(IntegrationParams integrationParams){
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.supportAuthType(integrationParams)) {
                    return authenticator;
                }
            }
        }
        return null;
    }
    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void clearCache(){
        cache.clear();
    }
}
